﻿namespace Amazon.Checkout.Handlers
{
    using System;
    using Models;
    using Orchard;
    using Orchard.ContentManagement;
    using Orchard.ContentManagement.Handlers;
    using Orchard.Data;
    using Orchard.Logging;

    public class CheckoutByAmazonButtonPartHandler : ContentHandler
    {
        private readonly IOrchardServices orchardServices;

        public CheckoutByAmazonButtonPartHandler(IOrchardServices orchardServices, IRepository<CheckoutByAmazonButtonPartRecord> repository)
        {
            this.orchardServices = orchardServices;

            OnLoading<ShoppingCartPart>(this.InitializeAmazonHelpers);
            OnLoading<CheckoutByAmazonButtonPart>(this.InitializeAmazonHelpers);

            Filters.Add(StorageFilter.For(repository));
        }

        private void InitializeAmazonHelpers(LoadContentContext context, object part)
        {
            var currentSite = this.orchardServices.WorkContext.CurrentSite;
            var settings = currentSite.As<SiteSettingsPart>();

            try
            {
                Helpers.AmazonCheckout.Initialize(
                    merchantId: settings.MerchantId,
                    awsAccessKeyId: settings.AwsAccessKeyId,
                    secretKeyId: settings.SecretKeyId,
                    associateTag: settings.AssociateTag,
                    currencyCode: settings.CurrencyCode,
                    lengthUnitOfMeasure: settings.LengthUnitOfMeasure,
                    volumeUnitOfMeasure: settings.VolumeUnitOfMeasure,
                    weightUnitOfMeasure: settings.WeightUnitOfMeasure,
                    jewelryWeightUnitOfMeasure: settings.JewelryWeightUnitOfMeasure,
                    degreeUnitOfMeasure: settings.DegreeUnitOfMeasure,
                    memorySizeUnitOfMeasure: settings.MemorySizeUnitOfMeasure,
                    frequencyUnitOfMeasure: settings.FrequencyUnitOfMeasure,
                    amperageUnitOfMeasure: settings.AmperageUnitOfMeasure,
                    timeUnitOfMeasure: settings.TimeUnitOfMeasure,
                    dateUnitOfMeasure: settings.DateUnitOfMeasure,
                    assemblyTimeUnitOfMeasure: settings.AssemblyTimeUnitOfMeasure,
                    ageRecommendedUnitOfMeasure: settings.AgeRecommendedUnitOfMeasure,
                    batteryPowerUnitOfMeasure: settings.BatteryPowerUnitOfMeasure,
                    voltageUnitOfMeasure: settings.VoltageUnitOfMeasure,
                    wattageUnitOfMeasure: settings.WattageUnitOfMeasure,
                    temperatureRatingUnitOfMeasure: settings.TemperatureRatingUnitOfMeasure,
                    clothingSizeUnitOfMeasure: settings.ClothingSizeUnitOfMeasure);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "An unexpected error occured while initilizing the Amazon Helper: {0}", ex.Message);
            }
        }
    }
}